import * as echarts from 'echarts';

/**
 * 根据 新增指标公式
 * 计算 指标对应值
 * @param {指标完整内容} newIndicator
 * @param {当前数据} rowData
 * @return {*} 当前指标对应值
 *
 **/
export const newIndicatorValue = (newIndicator: any, rowData: any): any => {
  // 指标类型为自定义指标
  if (newIndicator.type === '3') {
    let resultStr = '';
    // 自定义指标的 公式 遍历生成字符串运算 表达式
    newIndicator.computed?.forEach((el) => {
      switch (el.type) {
        case '1':
          // 四则运算及符号拼接为 字符串
          resultStr += el.name;
          break;
        case '2':
          resultStr += parseFloat(rowData[el.code]);
          break;
        default:
          break;
      }
    });
    /* eval 执行字符串表达式 */
    return eval(resultStr);
  }
};

const CustomGrammerType = (grammer: any, list: any, grammerNode: HTMLElement) => {
  if (grammer == null || list == null) return;

  if (grammer instanceof Array) {
    if (grammer.length <= 1) {
      alert('only 1 grammer config,need one more gramner to Y');
    }
    if (grammer.length > 2) {
      alert('no data match more then 2 grammer');
    }
  }
  //确定X轴公式
  const xZhou = grammer.data[0];
  //确定Y轴公式
  const yZhou = grammer.data[0];

  //获取X轴看板数据集合
  const xData = list.map((data: any) => {
    const xparam1name = xZhou.computed[0].code;
    const xparam1value = data[xZhou.computed[0].code];

    const xparam2name = xZhou.computed[2].code;
    const xparam2value = data[xZhou.computed[2].code];

    return {
      date: data.date,
      data: newIndicatorValue(xZhou, { [xparam1name]: xparam1value, [xparam2name]: xparam2value }),
    };
  });

  //获取Y轴看板数据集合
  const yData = list.map((data: any) => {
    const yparam1name = yZhou.computed[0].code;
    const yparam1value = data[yZhou.computed[0].code];

    const yparam2name = yZhou.computed[2].code;
    const yparam2value = data[yZhou.computed[2].code];

    return {
      date: data.date,
      data: newIndicatorValue(yZhou, { [yparam1name]: yparam1value, [yparam2name]: yparam2value }),
    };
  });

  const grammerData = echarts.init(grammerNode);

  const option = {
    title: {
      text: xZhou.name + yZhou.name + '表',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: [xZhou.name, 'Y 轴数据 ' + yZhou.name],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      name: xZhou.name,
      data: xData.map((data: any) => {
        return data.date;
      }),
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: xZhou.name,
        type: 'line',
        stack: 'Total',
        data: xData.map((data: any) => {
          return data.data;
        }),
      },
      {
        name: yZhou.name + 'Y',
        type: 'line',
        stack: 'Total',
        data: yData.map((data: any) => {
          return data.data;
        }),
      },
    ],
  };
  grammerData.setOption(option);
};

export default CustomGrammerType;
